package com.mocai.merchant.core;

import com.mocai.merchant.core.domain.annotation.Column;

import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * Created by Administrator on 2017/1/19.
 */
public class ReflectionUtils {

    public static String getColumnAnnotationName(Method method) {
        Column column = method.getAnnotation(Column.class);
        if (null != column) {
            return column.name();
        }
        return null;
    }

    public static String toGetMethodName(String fieldName) {
        return "get" + fieldName.substring(0, 1).toUpperCase() + fieldName.substring(1);
    }

    public static String toSetMethodName(String fieldName) {
        return "set" + fieldName.substring(0, 1).toUpperCase() + fieldName.substring(1);
    }

    public static String toFieldName(String methodName) {
        String returnValue = methodName.replaceFirst("(set|get)", "");
        return returnValue.substring(0, 1).toLowerCase() + returnValue.substring(1);
    }

    public static String toColumn(String str) {
        Pattern p = Pattern.compile("[A-Z]+");
        Matcher m = p.matcher(str);
        List<String> upperCases = new ArrayList<>();
        while (m.find()) {
            upperCases.add(m.group());
        }
        String[] lowerCases = str.split("[A-Z]+");

        StringBuffer returnValue = new StringBuffer();
        if (lowerCases[0].length() > 0) {
            returnValue.append(lowerCases[0]);
        }
        for (int i = 0; i < upperCases.size(); i++) {
            if (returnValue.length() > 0) {
                returnValue.append("_");
            }
            returnValue.append(upperCases.get(i).toLowerCase() + lowerCases[i + 1]);
        }
        return returnValue.toString();
    }
}
